package socket;

import org.apache.log4j.Logger;


public class RecvUtil {
	private static final  Logger log = Logger.getLogger(RecvUtil.class);
	public  String getFlag(String str){
		String flag=null;
		//初始化socket连接
		SocketClient sc=new SocketClient();
		log.info("send报文：["+str+"]");
		log.info("开始处理["+CutString.fsubstring(str,8,12).trim() +"]报文");
		String recvMsg=sc.sendMessage(str); 
		if(recvMsg.equals("nullerror")) return flag="未获取Socket，服务器监听未启动";
		if(recvMsg.equals("timeout")) return flag="接受服务器报文超时";
		if(recvMsg.equals("UnhostNameerror")) return flag="未知主机错误";
		if(recvMsg.equals("IOerror")) return flag="连接中断！IP不合法";
		if(recvMsg.equals("unerror")) return flag="未知错误";
		if(recvMsg.length()==69){
			return  "error:"+recvMsg.substring(recvMsg.length()-1, recvMsg.length());
		} 
		log.info("接收报文["+recvMsg+"]");
		if (recvMsg.getBytes().length<48) return flag="报文长度不合法"; 
		 //读取报文头
		String recvHead=recvMsg.substring(0,48);
		System.out.println("报文头："+recvHead);
		log.info("接收报文头["+recvHead+"]");
		//读取报文长度
		String msgLn=recvHead.substring(0,8);
		log.info("报文长度["+msgLn+"]");
		log.info("实际接受报文长度["+recvMsg.getBytes().length+"]");
		if (Integer.valueOf(msgLn)==recvMsg.getBytes().length) {
			//获取校验码
			String VerifyCode=recvHead.substring(40,48);
			log.info("接受报文校验码["+VerifyCode+"]");
			//读取报文体
			String recvBody=CutString.fsubstring(recvMsg,48,Integer.valueOf(msgLn));
			flag="1::"+recvBody;
			log.info("--校验码--"+CRC.getCRC32(recvBody));
			if (VerifyCode.equals(CRC.getCRC32(recvBody))) {
				System.out.println("报文体长度："+recvBody.getBytes().length);
				log.info("报文体长度["+recvBody.getBytes().length+"]");
				if (CutString.fsubstring(str,8,12).equals("9100")) {
					flag="1:::"+recvBody;
				}else {
					flag="1::"+recvBody;
				}
				
			}else{
				flag="接受报文校验码不合法";
			}
		}else {
			flag="接受报文长度不合法";
		}
		return flag;
	}
}
